package com.example.administrator.recycledemo;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Toast;

public class MyRecycleAdapter extends
        RecyclerView.Adapter<MyRecycleAdapterHolder> {

    private View headView;
    private View endView;
    private Context mContext;
    private int count;

    MyRecycleAdapter(Context mContext, int count) {
        this.count = count;
        this.mContext = mContext;
    }


    /**
     * 设置数据源总的条目
     */
    @Override
    public int getItemCount() {
        //返回条目数加头布局个数
        return count + 1;
    }

    @Override
    public void onBindViewHolder(MyRecycleAdapterHolder holder,
                                 final int position) {
        int itemViewType = getItemViewType(position);
        // 头部
        if (itemViewType == MainActivity.HEADER_RECYCLER_VIEW_ITEM) {
            return;
        } else if (itemViewType == MainActivity.END_RECYCLER_VIEW_ITEM) {
            return;
        } else if (itemViewType == MainActivity.NORMAL_RECYCLER_VIEW_ITEM) {//普通条目
            holder.iv_item_icon.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, (position - 1) + "", Toast.LENGTH_LONG).show();
                }
            });
        }

    }

    @Override
    public MyRecycleAdapterHolder onCreateViewHolder(ViewGroup parent,
                                                     int viewType) {
        View root = null;
        if (viewType == MainActivity.HEADER_RECYCLER_VIEW_ITEM) {
            root = headView;
        } else if (viewType == MainActivity.END_RECYCLER_VIEW_ITEM) {
            root = endView;
        } else {
            root = LayoutInflater.from(mContext).inflate(R.layout.item, parent,
                    false);
        }
        return new MyRecycleAdapterHolder(root, viewType);
    }

    /**
     * 添加自定义头部
     */
    public void addHeadView(View view) {
        this.headView = view;
    }

    /**
     * 添加自定义尾部
     */
    public void addEndView(View view) {
        this.endView = view;
    }

    @Override
    public int getItemViewType(int position) {

        if (position == 0) {
            return MainActivity.HEADER_RECYCLER_VIEW_ITEM;
        } else if (getItemCount() - 1 == position) {
            return MainActivity.END_RECYCLER_VIEW_ITEM;
        } else {
            return MainActivity.NORMAL_RECYCLER_VIEW_ITEM;
        }
    }
}